package logic

import (
	"context"
	"math/rand"
	"renting-demo/model/mysql"
	"renting-demo/order_srv/internal/svc"
	"renting-demo/order_srv/order"
	"strconv"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateLogic {
	return &CreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// todo: 生成订单
func (l *CreateLogic) Create(in *order.CreateOrderReq) (*order.Response, error) {

	price, name, count := mysql.GetPrice(strconv.Itoa(int(in.Userid)))
	//生成唯一随机订单号
	strs := "123467890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	rand.Seed(time.Now().UnixNano())
	b := make([]byte, 10)
	for i := range b {
		b[i] = strs[rand.Intn(len(strs))]
	}
	for s, f := range price {
		id, _ := strconv.Atoi(s)
		o := mysql.Order{
			OrderSn:    string(b),
			Userid:     in.Userid,
			Goodsid:    int64(id),
			Goodsname:  name[s],
			TotalPrice: f,
			Status:     0,
		}
		re := mysql.CreateOrder(o)
		if re.ID == 0 {
			return &order.Response{
				Status: "0",
			}, nil
		}
		p := mysql.OrderProduct{
			OrderId:    int64(re.ID),
			Userid:     in.Userid,
			Goodsid:    int64(id),
			Goodsname:  name[s],
			Goodsprice: f,
			Count:      int64(count[s]),
			Status:     0,
		}
		rf := mysql.CreateOrderProduct(p)
		if rf.ID == 0 {
			return &order.Response{
				Status: "0",
			}, nil
		}
	}

	return &order.Response{
		Status: "1",
	}, nil
}
